<template>
  <div class="app-container">
    <div class="org-container">
      <div class="org-tree">
        <el-tree
          :data="orgTree"
          :props="defaultProps"
          node-key="id"
          @node-click="handleNodeClick"
          default-expand-all
          :expand-on-click-node="false"
          class="tree-filter"
        >
          <template slot-scope="{ node, data }">
            <span>{{ data.name }}</span>
          </template>
        </el-tree>
      </div>
      <div class="org-table">
        <div class="filter-container">
          <el-input v-model="listQuery.name" placeholder="请输入名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
          <el-input v-model="listQuery.bianma" placeholder="请输入编码" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
          <el-select v-model="listQuery.depttype" placeholder="请选择类型" clearable class="filter-item" style="width: 130px">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            查询
          </el-button>
          <el-button v-if="listQuery.parentid != topOrgId" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleCreate">
            添加
          </el-button>
          <el-button v-else class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleSync">
            同步
          </el-button>
        </div>

        <el-table
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="bianma" label="编码" width="180" />
          <el-table-column prop="name" label="名称" width="200" />
          <el-table-column prop="type" label="类型" width="120" :formatter="formatType" />
          <el-table-column prop="bz" label="备注" min-width="150" />
          <el-table-column label="操作" width="150" fixed="right" align="center">
            <template slot-scope="{ row }">
              <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      </div>
    </div>

    <el-dialog :title="dialogStatus === 'create' ? '添加组织' : '编辑组织'" :visible.sync="dialogFormVisible" width="500px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="编码" prop="bianma">
          <el-input v-model="temp.bianma" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="temp.depttype" placeholder="请选择类型">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="bz">
          <el-input v-model="temp.bz" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'create'" label="上级组织">
          <el-select v-model="temp.parentid" placeholder="请选择上级组织">
            <el-option :value="0" label="无上级组织" />
            <el-option v-for="item in orgOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrgTree, getOrgListByCropId, createOrg, updateOrg, deleteOrg, syncOrg } from '@/api/org'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'

// 组织类型选项
const typeOptions = [
  { value: '7f01e2e5745cd0be872392c1c1ea57a7', label: '公司' },
  { value: 'e4069f9c7e4198b187c89529feb14c1d', label: '部门' }
]

export default {
  name: 'OrgManagement',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      orgTree: [],
      orgOptions: [],
      list: [],
      total: 0,
      listLoading: true,
      treeLoading: true,
      listQuery: {
        page: 1,
        size: 20,
        parentid: 0,
        name: '',
        bianma: '',
        depttype: '',
      },
      typeOptions,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      temp: {
        id: undefined,
        bianma: '',
        name: '',
        depttype: '',
        bz: '',
        parentid: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        bianma: [{ required: true, message: '请输入编码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        depttype: [{ required: true, message: '请选择类型', trigger: 'change' }]
      },
      // 记录下最顶级的组织机构ID，当选中这个ID时，只能同步子组织，当非此机构时，能向下添加组织
      topOrgId : undefined,
    }
  },
  created() {
    this.getOrgTree()
    // this.getList()
  },
  methods: {
    handleSync(){
      syncOrg().then(res=>{
        const {success,msg} = res;
        if(success){
          this.getOrgTree()
          this.$message.success('同步结果:'+msg)
        }else{
          this.$message.error('同步失败:'+msg)
        }
      })
    },
    getOrgTree() {
      this.treeLoading = true
      getOrgTree().then(response => {
        this.orgTree = response.data || []
        // 构建组织选项（扁平化处理）
        this.orgOptions = this.flattenTree(this.orgTree)
        this.treeLoading = false;
        if(this.orgOptions.length>0){
          this.listQuery.parentid = this.orgOptions[0].id;
          this.topOrgId = this.orgOptions[0].id;
          this.getList()
        }
        
      })
    },

    getList() {
      this.listLoading = true
      getOrgListByCropId({...this.listQuery}).then(response => {
        this.list = response.data.records || []
        this.total = response.data.total;
        this.listLoading = false
      })
    },

    handleFilter() {
      this.listQuery.page = 1;
      this.listQuery.cropId = 
      this.getList()
    },

    handleNodeClick(data) {
      this.listQuery.parentid = data.id
      this.handleFilter()
    },

    resetTemp() {
      this.temp = {
        id: undefined,
        bianma: '',
        name: '',
        depttype: '',
        bz: '',
        parentid: this.listQuery.parentid || 0
      }
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createOrg(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加组织成功',
              type: 'success',
              duration: 2000
            })
            // 刷新组织树和列表
            this.getOrgTree()
            this.getList()
          })
        }
      })
    },

    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateOrg(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新组织成功',
              type: 'success',
              duration: 2000
            })
            // 刷新组织树和列表
            this.getOrgTree()
            this.getList()
          })
        }
      })
    },

    handleDelete(row) {
      this.$confirm('确定要删除该组织吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrg({ id: row.id }).then(() => {
          this.$notify({
            title: '成功',
            message: '删除组织成功',
            type: 'success',
            duration: 2000
          })
          // 刷新组织树和列表
          this.getOrgTree()
          this.getList()
        })
      }).catch(() => {
        // 取消删除
      })
    },

    // 格式化类型显示
    formatType(row) {
  //     { value: '7f01e2e5745cd0be872392c1c1ea57a7', label: '公司' },
  // { value: 'e4069f9c7e4198b187c89529feb14c1d', label: '部门' }
      const typeMap = {
        '7f01e2e5745cd0be872392c1c1ea57a7': '公司',
        'e4069f9c7e4198b187c89529feb14c1d': '部门'
      }
      return typeMap[row.depttype] || row.depttype
    },

    // 扁平化树结构为选项列表
    flattenTree(tree, result = []) {
      tree.forEach(node => {
        result.push({
          id: node.id,
          name: node.name
        })
        if (node.children && node.children.length) {
          this.flattenTree(node.children, result)
        }
      })
      return result
    }
  },
  mounted() {
    // 添加样式
    const style = document.createElement('style')
    style.textContent = `
      .org-container {
        display: flex;
        height: calc(100vh - 120px);
      }
      .org-tree {
        width: 280px;
        overflow-y: auto;
        border-right: 1px solid #e6e6e6;
        padding: 10px;
      }
      .org-table {
        flex: 1;
        overflow-y: auto;
        padding: 10px;
      }
      .filter-container {
        margin-bottom: 16px;
        display: flex;
        align-items: center;
      }
      .filter-item {
        margin-right: 10px;
      }
      .tree-filter .el-tree-node__content {
        padding: 6px 0;
      }
    `
    document.head.appendChild(style)
  }
}
</script>
